<template>
  <div class="container">
    <!-- 编辑模式 -->
    <el-card v-show="isEdit" class="box-card">
      <template #header>
        <div class="card-header">
          <h3>编辑个人资料</h3>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="userInfo"
        :rules="rules"
        label-width="120px"
        class="user-form">
        <!-- 头像上传 -->
        <el-form-item label="头像" prop="avatar" style="align-items: center">
          <el-upload
            class="avatar-uploader"
            name="img"
            :action="uploadURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img
              v-if="userInfo.avatar"
              :src="userInfo.avatar || defaultAvatar"
              class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="el-upload__tip">
            <!-- 点击上传头像，只能上传jpg/png文件，且不超过1mb -->
          </div>
        </el-form-item>

        <!-- 昵称 -->
        <el-form-item label="昵称" prop="nickName" required>
          <el-input
            v-model="userInfo.nickName"
            placeholder="请输入昵称"
            maxlength="20"
            show-word-limit />
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="电子邮件" prop="email">
          <el-input
            v-model="userInfo.email"
            placeholder="请输入邮箱"
            type="email" />
        </el-form-item>

        <!-- 性别 -->
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userInfo.sex">
            <el-radio label="0">男</el-radio>
            <el-radio label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 按钮组 -->
        <el-form-item class="form-buttons">
          <el-button @click="cancelEdit">取 消</el-button>
          <el-button
            type="primary"
            :loading="loading"
            @click="submitForm(formRef)">
            保 存
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 查看模式 -->
    <el-card v-show="!isEdit" class="box-card">
      <template #header>
        <div class="card-header">
          <h3>个人资料</h3>
          <el-button type="primary" link @click="startEdit">
            <el-icon><Edit /></el-icon>
            编辑资料
          </el-button>
        </div>
      </template>

      <el-descriptions :column="1" border>
        <el-descriptions-item label="头像">
          <el-avatar :size="80" :src="userInfo.avatar" />
        </el-descriptions-item>

        <el-descriptions-item label="昵称">
          {{ userInfo?.nickName || '未设置' }}
        </el-descriptions-item>

        <el-descriptions-item label="电子邮件">
          {{ userInfo?.email || '未设置' }}
        </el-descriptions-item>

        <el-descriptions-item label="性别">
          {{ userInfo?.sex === '0' ? '男' : '女' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { Plus, Edit } from '@element-plus/icons-vue'
import defaultAvatar from '@/assets/images/tou.png'
import { useUserStore } from '@/store'
import { UserApi } from '@/api/user'

const userStore = useUserStore()
// 表单引用
const formRef = ref<FormInstance>()
const isEdit = ref(false)
const loading = ref(false)
const uploadURL = `${import.meta.env.VITE_APP_BASE_API}/upload`

const userInfo = computed(() => userStore.userInfo ?? {})

// 表单校验规则
const rules = ref<FormRules>({
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  email: [
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change'],
    },
  ],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
})

// 头像上传相关方法
const handleAvatarSuccess = (res: any) => {
  if (res.code === 200) {
    userInfo.value!.avatar = res.data
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error('上传图片失败')
  }
}

const beforeAvatarUpload = (file: File) => {
  const isValidFormat = ['image/jpeg', 'image/png', 'image/jpg'].includes(
    file.type
  )
  const isLt1M = file.size / 1024 / 1024 < 1

  if (!isValidFormat) {
    ElMessage.error('上传头像图片只能是 JPG/JPEG/PNG 格式!')
  }
  if (!isLt1M) {
    ElMessage.error('上传头像图片大小不能超过 1MB!')
  }

  return isValidFormat && isLt1M
}

// 表单操作方法
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 这里调用保存API
        const res = await UserApi.toUpdateUserInfo(userInfo.value)
        if (res.success) {
          // 刷新当前页面
          await userStore.toGetUserInfo()
          ElMessage.success('保存成功')
          isEdit.value = false
        }
      } catch (error) {
        ElMessage.error('保存失败')
      } finally {
        loading.value = false
      }
    }
  })
}

const startEdit = () => {
  isEdit.value = true
}

const cancelEdit = () => {
  formRef.value?.resetFields()
  isEdit.value = false
}

// 加载用户信息
const loadUserInfo = async () => {
  try {
    // 这里调用获取用户信息API
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.container {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 20px;
}

.box-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.user-form {
  max-width: 600px;
  margin: 0 auto;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader :deep(.el-upload) {
  border: 2px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 80px !important;
  height: 80px !important;
  border-radius: 50%;
  display: block;
  object-fit: cover;
}

.el-upload__tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 8px;
}

.form-buttons {
  margin-top: 32px;
  text-align: center;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input),
:deep(.el-select) {
  width: 100%;
  max-width: 320px;
}

:deep(.el-radio-group) {
  display: flex;
  gap: 32px;
}

:deep(.el-descriptions) {
  padding: 16px;
}

:deep(.el-descriptions__label) {
  width: 120px;
  color: var(--el-text-color-regular);
}

@media screen and (max-width: 768px) {
  .container {
    padding: 16px;
  }

  .user-form {
    padding: 0;
  }

  :deep(.el-form-item__label) {
    float: none;
    display: block;
    text-align: left;
    margin-bottom: 8px;
  }

  :deep(.el-input),
  :deep(.el-select) {
    max-width: 100%;
  }
}
</style>
